package com.atguigu.Threads.Exer;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 例子：创建三个窗口，售票总数为100
 * @author xiaoqi
 * @data 2021/04/04 20:20
 */
public class WindowTest {
    public static void main(String[] args) {
        //创建三个对象
        //线程不同步
        Window w1 = new Window();
        Window w2 = new Window();
        Window w3 = new Window();
        w1.setName("窗口一");
        w2.setName("窗口二");
        w3.setName("窗口三");
        w1.start();
        w2.start();
        w3.start();
    }

}
class Window extends Thread{
    //重写run
    //添加static和不添加static区别
//    public int ticket = 100;
    public static int ticket = 100;
    private ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + ":卖票，票号为" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
            finally {
                lock.unlock();
            }
        }
    }
}
